import { createRouter, createWebHistory } from "vue-router"
import routes from "./router"
import appStore from "@/stores"

// 用于存储页面滚动位置的Map
const scrollPositions = new Map()
// 暴露到window对象，以便在组件中访问
window.scrollPositions = scrollPositions

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
  scrollBehavior(to, from, savedPosition) {
    // 如果有保存的位置（浏览器前进后退），优先使用
    if (savedPosition) {
      return { top: savedPosition.top, behavior: "smooth" }
    }

    // 如果是从博客详情页返回到博客列表页，恢复之前保存的滚动位置
    if (from.name === "blogReader" && (to.name === "blogs" || to.name === "home")) {
      const savedScrollTop = scrollPositions.get("blogs")
      if (savedScrollTop !== undefined) {
        return { top: savedScrollTop, behavior: "smooth" }
      }
    }

    // 如果是从其他页面返回到博客列表页，也尝试恢复滚动位置
    if (to.name === "blogs" || to.name === "home") {
      const savedScrollTop = scrollPositions.get("blogs")
      if (savedScrollTop !== undefined) {
        return { top: savedScrollTop, behavior: "smooth" }
      }
    }

    // 其他情况滚动到顶部
    return { top: 0, behavior: "smooth" }
  },
})

// 路由守卫：在离开页面时保存滚动位置，并显示loading
router.beforeEach((to, from, next) => {
  // 如果是从博客列表页离开到博客详情页，保存当前滚动位置
  if ((from.name === "blogs" || from.name === "home") && to.name === "blogReader") {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop
    scrollPositions.set("blogs", scrollTop)
  }

  // 显示页面跳转loading
  if (appStore.homeviewStore) {
    appStore.homeviewStore.showPageLoading()
  }

  next()
})

export default router
